package com.example.newsmanager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.newsmanager.dao.UserMapper;
import com.example.newsmanager.entity.DTO.LoginDTO;
import com.example.newsmanager.entity.DTO.RegisterDTO;
import com.example.newsmanager.entity.User;
import com.example.newsmanager.service.UserService;
import com.example.newsmanager.util.JwtUtil;
import com.example.newsmanager.util.RandomUtil;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private RedisTemplate<String,Object> template;

    @Autowired
    private UserMapper userMapper;

    @Override
    public String userLogin(LoginDTO loginDTO) {
        LambdaQueryWrapper<User> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(User::getUserId,loginDTO.getLoginCondition())
                .eq(User::getPassword,loginDTO.getPassword());
        User loginUser = userMapper.selectOne(wrapper1);
        if(loginUser == null){
            LambdaQueryWrapper<User> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(User::getNickname,loginDTO.getLoginCondition())
                    .eq(User::getPassword,loginDTO.getPassword());
            loginUser = userMapper.selectOne(wrapper2);
        }
        if(loginUser == null){
            LambdaQueryWrapper<User> wrapper3 = new LambdaQueryWrapper<>();
            wrapper3.eq(User::getEmail,loginDTO.getLoginCondition())
                    .eq(User::getPassword,loginDTO.getPassword());
            loginUser = userMapper.selectOne(wrapper3);
        }
        if(loginUser != null){
            String key = "user"+loginUser.getUserId();
            loginUser.setLoginTime(Timestamp.valueOf(LocalDateTime.now()));
            userMapper.updateById(loginUser);
            template.opsForValue().set(key,loginUser,6, TimeUnit.HOURS);
            return JwtUtil.createJwt(key);
        }
        return null;
    }

    @Override
    public String adminLogin(LoginDTO loginDTO) {
        LambdaQueryWrapper<User> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(User::getUserId,loginDTO.getLoginCondition())
                .eq(User::getPassword,loginDTO.getPassword());
        User loginUser = userMapper.selectOne(wrapper1);
        if(loginUser == null){
            LambdaQueryWrapper<User> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.eq(User::getNickname,loginDTO.getLoginCondition())
                    .eq(User::getPassword,loginDTO.getPassword());
            loginUser = userMapper.selectOne(wrapper2);
        }
        if(loginUser == null){
            LambdaQueryWrapper<User> wrapper3 = new LambdaQueryWrapper<>();
            wrapper3.eq(User::getEmail,loginDTO.getLoginCondition())
                    .eq(User::getPassword,loginDTO.getPassword());
            loginUser = userMapper.selectOne(wrapper3);
        }
        if(loginUser != null){
            if(loginUser.getUserType().equals(2)||loginUser.getUserType().equals(3)){
                String key = "user"+loginUser.getUserId();
                loginUser.setLoginTime(Timestamp.valueOf(LocalDateTime.now()));
                userMapper.updateById(loginUser);
                template.opsForValue().set(key,loginUser,6, TimeUnit.HOURS);
                return JwtUtil.createJwt(key);
            }
            return null;
        }
        return null;
    }

    @Override
    public Map<String, Object> getUserDetail(String userId) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        User user = userMapper.selectOne(wrapper.eq(User::getUserId,userId));
        Map<String,Object> userMap = new HashMap<>();
        userMap.put("userId",user.getUserId());
        userMap.put("nickname",user.getNickname());
        userMap.put("avatar",user.getAvatar());
        userMap.put("gender",user.getGender());
        userMap.put("age",user.getAge());
        userMap.put("userType",user.getUserType());
        userMap.put("loginTime",user.getLoginTime());
        userMap.put("email",user.getEmail());
        userMap.put("signature",user.getSignature());
        return userMap;
    }


    @Override
    public Map<String,Object> userRegister(RegisterDTO registerDTO) {
        LambdaQueryWrapper<User> wrapper1 = new LambdaQueryWrapper<>();
        String key = "msg_"+registerDTO.getEmail();
        String code = (String) template.opsForValue().get(key);
        if(registerDTO.getCode().equals(code)){
            template.delete(key);
            User registerUser = userMapper.selectOne(wrapper1.eq(User::getNickname,registerDTO.getNickname()));
            if(registerUser == null){
                LambdaQueryWrapper<User> wrapper2 = new LambdaQueryWrapper<>();
                registerUser = userMapper.selectOne(wrapper2.eq(User::getEmail,registerDTO.getEmail()));
            }
            if(registerUser == null){
                User user = new User();
                Map<String, Object> data = new HashMap<>();
                String userId = RandomUtil.generateRandom11DigitsAsString();
                user.setUserType(1);
                user.setUserId(userId);
                user.setNickname(registerDTO.getNickname());
                user.setPassword(registerDTO.getPassword());
                user.setEmail(registerDTO.getEmail());
                user.setRegisterTime(Timestamp.valueOf(LocalDateTime.now()));
                userMapper.insert(user);
                data.put("userId",userId);
                return data;
            }
            return null;
        }
        return null;
    }

    @Override
    public List<User> getAllUserService(Integer pages) {
        //设置分页参数
        Page<User> page = new Page<>(pages, 6);
        userMapper.selectPage(page, null);
        //获取分页数据
        return page.getRecords();
    }
}
